InterfaceAndDevice.py

Control Camera(s) Connected to Frame Grabber(s)

It shows how to enumerate one or more cameras connected to the self-developed frame grabber via enumeration APIs, and perform operations such as turning on cameras and grabbing images.

1 # -- coding: utf-8 --
2 
3 import sys
4 import platform
5 import os
6 from ctypes import *
7 
8 # Compatible with different operating systems to load DDL
9 currentsystem = platform.system()
10 if currentsystem == 'Windows':
11  sys.path.append(os.path.join(os.getenv('MVCAM_COMMON_RUNENV'), "Samples", "Python", "MvImport"))
12 else:
13  sys.path.append(os.path.join("..", "..", "MvImport"))
14 
15 from MvCameraControl_class import *
16 
17 
18 # Compatible with input processing of Python 2.X and 3.X
19 if sys.version_info[0] < 3:
20  # Python 2.x
21  input_func = raw_input
22 else:
23  # Python 3.x
24  input_func = input
25 
26 # Decoding Characters
27 def decoding_char(ctypes_char_array):
28  """
29  Safely decode a string from a ctypes character array.
30  Compatible with Python 2.x and 3.x, as well as 32-bit and 64-bit environments.
31  """
32  byte_str = memoryview(ctypes_char_array).tobytes()
33 
34  # Truncate at the first null character
35  null_index = byte_str.find(b'\x00')
36  if null_index != -1:
37  byte_str = byte_str[:null_index]
38 
39  # Attempt to decode using multiple encodings
40  for encoding in ['gbk', 'utf-8', 'latin-1']:
41  try:
42  return byte_str.decode(encoding)
43  except UnicodeDecodeError:
44  continue
45 
46  # If all encodings fail, use a replacement strategy
47  return byte_str.decode('latin-1', errors='replace')
48 
49 fun_ctype = get_platform_functype()
50 
51 stFrameInfo = POINTER(MV_FRAME_OUT_INFO_EX)
52 pData = POINTER(c_ubyte)
53 FrameInfoCallBack = fun_ctype(None, pData, stFrameInfo, c_void_p)
54 
55 
56 def image_callback(pData, pFrameInfo, pUser):
57  stFrameInfo = cast(pFrameInfo, POINTER(MV_FRAME_OUT_INFO_EX)).contents
58  if stFrameInfo:
59  print("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (stFrameInfo.nWidth, stFrameInfo.nHeight, stFrameInfo.nFrameNum))
60 
61 CALL_BACK_FUN = FrameInfoCallBack(image_callback)
62 
63 
64 def print_devices_info(deviceList):
65  for i in range(0, deviceList.nDeviceNum):
66  mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
67  if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE or mvcc_dev_info.nTLayerType == MV_GENTL_GIGE_DEVICE:
68  print ("\ngige device: [%d]" % i)
69  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName)
70  print ("device model name: %s" % strModeName)
71 
72  nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
73  nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
74  nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
75  nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
76  print ("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
77  elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
78  print ("\nu3v device: [%d]" % i)
79  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chModelName)
80  print ("device model name: %s" % strModeName)
81 
82  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber)
83  print ("user serial number: %s" % strSerialNumber)
84  elif mvcc_dev_info.nTLayerType == MV_GENTL_CAMERALINK_DEVICE:
85  print ("\nCML device: [%d]" % i)
86  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stCMLInfo.chModelName)
87  print ("device model name: %s" % strModeName)
88 
89  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stCMLInfo.chSerialNumber)
90  print ("user serial number: %s" % strSerialNumber)
91  elif mvcc_dev_info.nTLayerType == MV_GENTL_CXP_DEVICE:
92  print ("\nCXP device: [%d]" % i)
93  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stCXPInfo.chModelName)
94  print ("device model name: %s" % strModeName)
95 
96  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stCXPInfo.chSerialNumber)
97  print ("user serial number: %s" % strSerialNumber)
98  elif mvcc_dev_info.nTLayerType == MV_GENTL_XOF_DEVICE:
99  print ("\nXoF device: [%d]" % i)
100  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stXoFInfo.chModelName)
101  print ("device model name: %s" % strModeName)
102 
103  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stXoFInfo.chSerialNumber)
104  print ("user serial number: %s" % strSerialNumber)
105 
106 
107 def print_interface_info(interfaceList):
108  for i in range(0, interfaceList.nInterfaceNum):
109  interfaceInfo = cast(interfaceList.pInterfaceInfos[i], POINTER(MV_INTERFACE_INFO)).contents
110  print("interface: [%d]" % i)
111 
112  displayName = decoding_char(interfaceInfo.chDisplayName)
113  print("display name: %s" % displayName)
114 
115  serialNumber = decoding_char(interfaceInfo.chSerialNumber)
116  print("serial number: %s" % serialNumber)
117 
118  modelName = decoding_char(interfaceInfo.chModelName)
119  print("model name: %s" % modelName)
120 
121  interfaceId = decoding_char(interfaceInfo.chInterfaceID)
122  print("interface id: %s" % interfaceId)
123 
124 
125 if __name__ == "__main__":
126 
127  try:
128  # Initialize SDK resources
129  MvCamera.MV_CC_Initialize()
130 
131  SDKVersion = MvCamera.MV_CC_GetSDKVersion()
132  print ("SDKVersion[0x%x]" % SDKVersion)
133 
134  interfaceList = MV_INTERFACE_INFO_LIST()
135  transportLayerType = MV_GIGE_INTERFACE | MV_CAMERALINK_INTERFACE | MV_CXP_INTERFACE | MV_XOF_INTERFACE
136 
137  # Enumerate frame grabbers
138  ret = MvCamera.MV_CC_EnumInterfaces(transportLayerType, interfaceList)
139  if ret != 0:
140  print("enum interfaces fail! ret[0x%x]" % ret)
141  sys.exit()
142 
143  if interfaceList.nInterfaceNum == 0:
144  print("find no interface!")
145  sys.exit()
146 
147  print("Find %d interfaces!" % interfaceList.nInterfaceNum)
148  print_interface_info(interfaceList)
149 
150  nInterfaceIndex = input_func("please input the number of the interface to connect:")
151 
152  if int(nInterfaceIndex) >= interfaceList.nInterfaceNum:
153  print("input error!")
154  sys.exit()
155 
156  # Create a camera instance
157  cam_instance = MvCamera()
158  interface_instance = MvCamera()
159 
160  # Select the frame grabber, and create a handle
161  curInterface = cast(interfaceList.pInterfaceInfos[int(nInterfaceIndex)], POINTER(MV_INTERFACE_INFO)).contents
162 
163  ret = interface_instance.MV_CC_CreateInterface(curInterface)
164  if ret != 0:
165  raise Exception("create interface handle fail! ret[0x%x]" % ret)
166 
167  # Turn on the device
168  ret = interface_instance.MV_CC_OpenInterface()
169  if ret != 0:
170  raise Exception("open interface fail! ret[0x%x]" % ret)
171  else:
172  print("open interface success")
173 
174  # Enumerates cameras connected to the frame grabber
175  deviceList = MV_CC_DEVICE_INFO_LIST()
176  ret = interface_instance.MV_CC_EnumDevicesByInterface(deviceList)
177  if ret != 0:
178  raise Exception("enum devices fail! ret[0x%x]" % ret)
179 
180  if deviceList.nDeviceNum == 0:
181  raise Exception("find no device!")
182 
183  print_devices_info(deviceList)
184 
185  nCamIndex = input_func("please input the number of the device to connect:")
186 
187  if int(nCamIndex) >= deviceList.nDeviceNum:
188  raise Exception("input error!")
189 
190  # Select a device, and create a handle
191  stDeviceList = cast(deviceList.pDeviceInfo[int(nCamIndex)], POINTER(MV_CC_DEVICE_INFO)).contents
192 
193  ret = cam_instance.MV_CC_CreateHandle(stDeviceList)
194  if ret != 0:
195  raise Exception("create handle fail! ret[0x%x]" % ret)
196 
197  # Turn on the device
198  ret = cam_instance.MV_CC_OpenDevice(MV_ACCESS_Exclusive, 0)
199  if ret != 0:
200  raise Exception("open device fail! ret[0x%x]" % ret)
201 
202  # Get optimal packet size (only supported by GigE devices)
203  if stDeviceList.nTLayerType == MV_GIGE_DEVICE or stDeviceList.nTLayerType == MV_GENTL_GIGE_DEVICE:
204  nPacketSize = cam_instance.MV_CC_GetOptimalPacketSize()
205  if int(nPacketSize) > 0:
206  ret = cam_instance.MV_CC_SetIntValue("GevSCPSPacketSize", nPacketSize)
207  if ret != 0:
208  print("Warning: Set Packet Size fail! ret[0x%x]" % ret)
209  else:
210  print("Warning: Get Packet Size fail! ret[0x%x]" % nPacketSize)
211 
212  # Set trigger mode to off
213  ret = cam_instance.MV_CC_SetEnumValue("TriggerMode", MV_TRIGGER_MODE_OFF)
214  if ret != 0:
215  raise Exception("set trigger mode fail! ret[0x%x]" % ret)
216 
217  #Register an image grabbing callback
218  ret = cam_instance.MV_CC_RegisterImageCallBackEx(CALL_BACK_FUN, None)
219  if ret != 0:
220  raise Exception("register image callback fail! ret[0x%x]" % ret)
221 
222  # Start grabbing images
223  ret = cam_instance.MV_CC_StartGrabbing()
224  if ret != 0:
225  raise Exception("start grabbing fail! ret[0x%x]" % ret)
226 
227  print ("press Enter key to stop grabbing.")
228  input_func()
229 
230  # Stop grabbing images
231  ret = cam_instance.MV_CC_StopGrabbing()
232  if ret != 0:
233  raise Exception("stop grabbing fail! ret[0x%x]" % ret)
234 
235  # Turn off the device
236  ret = cam_instance.MV_CC_CloseDevice()
237  if ret != 0:
238  raise Exception("close deivce fail! ret[0x%x]" % ret)
239 
240  # Destroy the handle
241  cam_instance.MV_CC_DestroyHandle()
242 
243  # Turn off the frame grabber
244  interface_instance.MV_CC_CloseInterface()
245 
246  # Destroy frame grabber handle
247  interface_instance.MV_CC_DestroyInterface()
248  except Exception as e:
249  print(e)
250  cam_instance.MV_CC_CloseDevice()
251  cam_instance.MV_CC_DestroyHandle()
252  interface_instance.MV_CC_CloseInterface()
253  interface_instance.MV_CC_DestroyInterface()
254 
255  finally:
256  # Release SDK resources
257  MvCamera.MV_CC_Finalize()